import os
import socket
import json
import time
from datetime import datetime
import threading
import sys
import requests
import schedule
import time
from datetime import datetime
import urllib3
is_debug = False
HOST = 'seestar.local' #sys.argv[1]
PORT = 4700
cmdid = 999
s = None
save_path = 'Z://S50'
def send_message(data):
    global s
    try:
        s.sendall(data.encode())  # TODO: would utf-8 or unicode_escaped help here
    except socket.error as e:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((HOST, PORT))
        except:
            return
        send_message(data)
def get_socket_msg():
    global s
    try:
        data = s.recv(1024 * 60)  # comet data is >50kb
    except socket.error as e:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((HOST, PORT))
            data = s.recv(1024 * 60)
        except:
            return ""
    data = data.decode("utf-8")
    if is_debug:
        print("Received :", data)
    return data
def json_message(instruction):
    global cmdid
    data = {"id":cmdid, "method": instruction,"params":{"is_subframe":True, "is_thumb":False}}
    # data = {"ClientID":1,"ClientTransactionID": cmdid, "Action": instruction, "Parameters": {"is_subframe": True, "is_thumb": False}}
    cmdid += 1
    json_data = json.dumps(data)
    if is_debug:
        print("Sending %s" % json_data)
    send_message(json_data + "\r\n")
def get_last_image_fits_url():
    global HOST
    global PORT
    global s
    global cmdid
    global is_debug
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((HOST, PORT))
    except:
        print("###连接超时，S50可能关机或者断网")
        return ""
    with s:
        # flush the socket input stream for garbage
        get_socket_msg()
        if True:
            json_message("get_albums")
            # time.sleep(5)
            try:
                data = get_socket_msg()
            except:
                print("#接受数据失败或中断")
                return ""
            # print(data)
            try:
                parsed_data = json.loads(data)
            except:
                print("#返回值解析错误")
                try:
                    s.shutdown(socket.SHUT_RDWR)
                    return ""
                except:
                    return ""
                # sys.exit()
            print(parsed_data)
            album_result = None
            first_list = []
            try:
                album_result = parsed_data["result"]
                first_list = album_result["list"][0]
            except:
                print("#获取URL异常，忽略")
                return  ""
            result_url = ""
            result_name = None
            print("#first_list: ", first_list)
            for files in first_list["files"]:
                if (files["name"].endswith("-sub")) :
                    result_url = files["thn"]
                    result_name = files["name"]
                    result_url = result_url.partition("_thn.jpg")[0] + ".fit"
                    break
            # print(result_url)
    # s.close()

    last_image_url =  'http://'+HOST+'/MyWorks/'+  result_url
    if is_debug:
        print(last_image_url)
    try:
        s.shutdown(socket.SHUT_RDWR)
        return last_image_url
    except:
        return last_image_url
# 定义下载函数
def download_file(url, save_path):
    output_filename_short=str(url.split('/')[-1]).replace('\'','').replace('Light_','T_CrB_')
    print("#输出文件名:{}".format(output_filename_short))
    FITDATE=output_filename_short.split('-')[0][-8:]
    print("#从url获得拍摄日期:{}".format(FITDATE))
    save_path=os.path.join(save_path,FITDATE)
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    output_filename = os.path.join(save_path,output_filename_short )
    if os.path.isfile(output_filename):
        print(f'#文件已存在,忽略下载: {output_filename}')
    else:
        http = urllib3.PoolManager()
        response = http.request('GET', url, preload_content=False)
        if response.status == 200:
            print("#存储到:{}".format(output_filename))
            with open(output_filename, 'wb') as out:
                out.write(response.data)
        else:
            print(f'#下载失败，状态码: {response.status}')
        response.release_conn()
# 定义定时任务函数
def download_task(save_path):
    # 获取当前日期和时间
    now = datetime.now()
    current_date_time = now.strftime("%Y-%m-%d %H:%M:%S")
    # 打印当前日期和时间
    print("------拉取最新fit文件任务{}:{}-------".format(cmdid,current_date_time))
    last_image_url = get_last_image_fits_url()
    if last_image_url != "":
        download_file(last_image_url, save_path)
    else:
        print('#未能从S50获取最新fit文件URL')
# 设置定时任务
def schedule_download( save_path, interval):
    schedule.every(interval).seconds.do(download_task, save_path)
    while True:
        schedule.run_pending()
        time.sleep(1)
if __name__ == "__main__":
    schedule_download( save_path, 30)

